﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarPark.Helper;

namespace CarPark.MainModel
{
    public partial class Main : Form
    {

        #region Field

        /// <summary>
        /// 当前车库的ID号，表示以后操作都是针对该车库的
        /// </summary>
        private int ckid = -1;
        //业务逻辑类
        private MidCarPark mcp = new MidCarPark();
        //标记用户管理中查询的是什么什么类型的数据1-用户信息2-充值记录3-停车记录
        private int user_flag = 0;
        //COM1接收缓存
        private byte[] rbuff1;
        //COM2接收缓存
        private byte[] rbuff2;
        //串口辅助对象
        private SerialPortHelper sph = new SerialPortHelper();
        //测试用发送
        private byte[] send1;

        #endregion


        #region Property

        public int CKID
        {
            get { return ckid; }
            set { ckid = value; }
        }
        public string KNAME
        {
            get;
            set;
        }

        #endregion

        #region delegate

        public EventHandler DealParentToMain;


        #endregion

        public Main(FrmParent parent)
        {
            InitializeComponent();
            //自我构造
            DealParentToMain = DealParentToMainHandle;
            this.MdiParent = parent;
            userAdd1.Hide();

            //窗体关闭事件
            this.FormClosing += new FormClosingEventHandler(Main_FormClosing);
            //tabcontrol选择变化
            this.tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);
            //选择车型下拉框选择变化
            this.cmbChooseCarModel.SelectedIndexChanged += new EventHandler(cmbChooseCarModel_SelectedIndexChanged);

            LoadInsideCars(255);
            //测试用
            send1 = new byte[4];
            send1[0] = 0xFC;
            send1[1] = 0x23;
            send1[2] = 0x11;
            send1[3] = 0x00;

        }



        void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            e.Cancel = true;
            base.OnFormClosing(e);
        }

        #region private method

        void DealParentToMainHandle(object sender, EventArgs e)
        {
            ParentToMainEventArg arg = e as ParentToMainEventArg;
            if (null != arg)
            {
                CKID = arg.CKID;
                if (CKID > 0)
                {
                    SetParkName();
                    FreshAvCount();

                    //to do other things
                }
                else
                    this.lblShenYuCheWei.Text = "当前车库：" + CKID.ToString() + " " + "剩余车位：";
            }
            else
                MessageBox.Show(GlobalConst.GLOBAL_MISSING_ARG, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
        }
        
        /// <summary>
        /// 刷新车型列表
        /// </summary>
        private void FreshCarModelCombo()
        {
            cmbChooseCarModel.DataSource = null;
            cmbChooseCarModel.DataSource = mcp.GetAllCarModel();
        }

        /// <summary>
        /// 刷新剩余车位
        /// </summary>
        private void FreshAvCount()
        {
            int syCount = 0;
            string get = mcp.AvCount(CKID, ref syCount);
            if (get == GlobalConst.CK_OK)
            {
                this.lblShenYuCheWei.Text = "当前车库：" + KNAME + " " + "剩余车位：" + syCount.ToString();
            }
            else
            {
                this.lblShenYuCheWei.Text = "当前车库：" + KNAME + " " + "剩余车位：";
                MessageBox.Show(GlobalConst.PARENT_SYCOUNT_FAILED + "\n错误信息：\n" + get, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
        }
        private void SetParkName()
        {
            string pname = string.Empty;
            if (GlobalConst.CK_OK == mcp.ParkName(CKID, ref pname))
            {
                KNAME = pname;
            }
            
        }
        #endregion

        #region events handler

        /// <summary>
        /// tabcontrol 选择变化时，处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedTab.Name)
            {
                case "pgeCKInfo":
                    break;
                case "pgeUserManage":
                    break;
                case "pgePriceManage":
                    FreshCarModelCombo();
                    break;
                default:
                    break;
            }
        }


        /// <summary>
        /// 选择车型下拉框选择变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbChooseCarModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (null != cmbChooseCarModel.SelectedItem)
                txtCarPriceShow.Text = (cmbChooseCarModel.SelectedItem as MidCarPark.CarModel).CarPrice.ToString();
        }

        /// <summary>
        /// 删除车型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelCar_Click(object sender, EventArgs e)
        {
            MidCarPark.CarModel cm = cmbChooseCarModel.SelectedItem as MidCarPark.CarModel;
            if (null != cm)
            {
                if (cm.CarModelNumber > -1)
                {
                    string ret = mcp.DeleteCarModel(cm);
                    if (ret == GlobalConst.CK_OK)
                    {
                        MessageBox.Show(GlobalConst.PARENT_DELCARMODEL_SUCCESS, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                        FreshCarModelCombo();
                    }
                    else
                        MessageBox.Show(GlobalConst.PARENT_DELCARMODEL_FAILED + "\n错误信息：\n" + ret, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                }
                else
                    MessageBox.Show(GlobalConst.PARENT_CARCHOOSE_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
            else
                MessageBox.Show(GlobalConst.PARENT_CARCHOOSE_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
        }

        /// <summary>
        /// 新增车型按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddNewCarModel_Click(object sender, EventArgs e)
        {
            if (txtNewCarModel.Text == string.Empty)
            {
                MessageBox.Show(GlobalConst.PARENT_CARMODELNAME_EMPTY, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
            else if (txtNewCarPrice.Text == string.Empty)
            {
                MessageBox.Show(GlobalConst.PARENT_CARMODELPRICE_EMPTY, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
            else
            {
                double price;
                try
                {
                    price = Convert.ToDouble(txtNewCarPrice.Text);
                    string ret;
                    ret = mcp.AddCarModel(new MidCarPark.CarModel(txtNewCarModel.Text, price));
                    if (ret == GlobalConst.CK_OK)
                    {
                        MessageBox.Show(GlobalConst.PARENT_CARMODELADD_SUCCESS, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                        FreshCarModelCombo();
                    }
                    else
                        MessageBox.Show(GlobalConst.PARENT_CARMODELADD_FAILED + "\n错误信息：\n" + ret, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                }
                catch
                {
                    MessageBox.Show(GlobalConst.PARENT_CARMODELPRICE_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                }
            }
        }

        /// <summary>
        /// 修改单价按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCarPriceModify_Click(object sender, EventArgs e)
        {
            MidCarPark.CarModel cm = cmbChooseCarModel.SelectedItem as MidCarPark.CarModel;
            if (null != cm)
            {
                if (cm.CarModelNumber > -1)
                {
                    try
                    {
                        double newPrice = Convert.ToDouble(txtCarPriceShow.Text);
                        string ret = mcp.UpdateCarPrice(cm, newPrice);
                        if (ret == GlobalConst.CK_OK)
                        {
                            MessageBox.Show(GlobalConst.PARENT_UPDATECARMODEL_SUCCESS, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                            FreshCarModelCombo();
                        }
                        else
                            MessageBox.Show(GlobalConst.PARENT_UPDATECARMODEL_FAILED + "\n错误信息：\n" + ret, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                    }
                    catch
                    {
                        MessageBox.Show(GlobalConst.PARENT_CARMODELPRICE_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                    }
                }
                else
                    MessageBox.Show(GlobalConst.PARENT_CARCHOOSE_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
            else
                MessageBox.Show(GlobalConst.PARENT_CARCHOOSE_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
        }

        /// <summary>
        /// 放行按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIn_Click(object sender, EventArgs e)
        {
            if (txtInOrOutCardID.Text == string.Empty)
            {
                MessageBox.Show(GlobalConst.PARENT_ACCESS_EMPTY, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
            else
            {
                Int64 cardid;
                try
                {
                    cardid = Convert.ToInt64(txtInOrOutCardID.Text);
                    string ret;
                    ret = mcp.CarInOut(CKID, cardid);
                    if (ret == GlobalConst.CK_OK)
                    {
                        sph.OpenFence(serialPort2);
                        MessageBox.Show("打开护栏，放行！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                    }
                    else
                        MessageBox.Show(GlobalConst.PARENT_ACCESS_FAILED + "\n错误信息：\n" + ret, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                }
                catch
                {
                    MessageBox.Show(GlobalConst.PARENT_ACCESS_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                }
            }
            
            LoadInsideCars(255);
            FreshAvCount();
        }

        /// <summary>
        /// 充值按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddMoney_Click(object sender, EventArgs e)
        {
            if (txtUserCardID.Text == string.Empty && txtUserCarNumber.Text == string.Empty)
                MessageBox.Show("请输入用户的卡号或者车牌号！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            else if (txtAddMoney.Text == string.Empty)
                MessageBox.Show("必须填写金额！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            else
            {
                double money;
                try
                {
                    money = Convert.ToDouble(txtAddMoney.Text);
                    if (money <= 0)
                        MessageBox.Show("金额必须大于零！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                    else
                    {
                        string cardid = txtUserCardID.Text;
                        string UserInfo = mcp.GetCurrentUserInfoByString(ref cardid, txtUserCarNumber.Text);
                        if (UserInfo == GlobalConst.CK_NOUSER)
                            MessageBox.Show("没有这个用户，请重新输入卡号或车牌！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                        else
                        {
                            if (MessageBox.Show(string.Format("将要为{0}充值人民币：{1}",
                                            UserInfo,
                                            money.ToString()), GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OKCancel) == DialogResult.OK)
                            {
                                if (mcp.AddUserMoney(cardid, txtUserCarNumber.Text, money) == GlobalConst.CK_OK)
                                {
                                    MessageBox.Show(string.Format("充值成功\n{0}", mcp.GetCurrentUserInfoByString(ref cardid, txtUserCarNumber.Text)), GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                                }
                                else
                                    MessageBox.Show("充值失败！");
                            }
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("金额输入格式不正确", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                }
            }
        }

        /// <summary>
        /// 查询余额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchBalance_Click(object sender, EventArgs e)
        {
            if (txtUserCardID.Text == string.Empty && txtUserCarNumber.Text == string.Empty)
                MessageBox.Show("请输入用户的卡号或者车牌号！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            else
            {
                string cardid = txtUserCardID.Text;
                string UserInfo = mcp.GetCurrentUserInfoByString(ref cardid, txtUserCarNumber.Text);
                if (UserInfo == GlobalConst.CK_NOUSER)
                    MessageBox.Show("没有这个用户，请重新输入卡号或车牌！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                else
                {
                    string ret;
                    double moeny;
                    ret = mcp.GetUserBalance(cardid, out moeny);
                    if (ret == GlobalConst.CK_OK)
                        MessageBox.Show(string.Format("卡号：{0}\n剩余金额：{1}", cardid, moeny), GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                    else
                        MessageBox.Show("查询失败！" + "\n错误信息：\n" + ret, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
                }
            }
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUserQuery_Click(object sender, EventArgs e)
        {
            Int64 cardid;
            try
            {
                cardid = Convert.ToInt64(txtUserQueryCardId.Text);
                GridViewUser.DataSource = mcp.GetUserInfo(cardid.ToString());
                user_flag = 1;
            }
            catch
            {
                MessageBox.Show("请正确填写卡号格式！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
        }

        /// <summary>
        /// 查询充值记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChargeRecord_Click(object sender, EventArgs e)
        {
            Int64 cardid;
            try
            {
                cardid = Convert.ToInt64(txtUserQueryCardId.Text);
                GridViewUser.DataSource = mcp.GetUserChargeRecord(cardid.ToString());
                user_flag = 2;
            }
            catch
            {
                MessageBox.Show("请正确填写卡号格式！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
        }

        /// <summary>
        /// 查询停车记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCostRecord_Click(object sender, EventArgs e)
        {
            Int64 cardid;
            try
            {
                cardid = Convert.ToInt64(txtUserQueryCardId.Text);
                GridViewUser.DataSource = mcp.GetUserCostRecord(cardid.ToString());
                user_flag = 2;
            }
            catch
            {
                MessageBox.Show("请正确填写卡号格式！", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
        }

        /// <summary>
        /// 用户表GridViewUser数据源变动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridViewUser_DataSourceChanged(object sender, EventArgs e)
        {
            if (GridViewUser.DataSource != null)
            {
                switch (user_flag)
                {
                    case 1:
                        lblUserDataGridViewTitle.Text = "用户信息列表";
                        break;
                    case 2:
                        lblUserDataGridViewTitle.Text = "用户充值记录列表";
                        break;
                    case 3:
                        lblUserDataGridViewTitle.Text = "用户停车记录列表";
                        break;
                    default:
                        lblUserDataGridViewTitle.Text = "无记录";
                        break;
                }
            }
            else
            {
                lblUserDataGridViewTitle.Text = "查询出错";
            }
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            userAdd1.LoadValues();
            userAdd1.Show();
        }


        /// <summary>
        /// 查询车库情况
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, EventArgs e)
        {
            LoadInsideCars(0);
        }
        private void LoadInsideCars(Byte type)
        {
            long paraCardid = 0;
            string carTag = txtQueryCarNumber.Text.Trim();
            if (txtQueryCardID.Text != string.Empty)
            {
            //    if (txtQueryCarNumber.Text != string.Empty)
            //    {
            //        mcp.GetCardIDorCarTag(ref paraCardid, ref carTag);
            //        if(paraCardid == 0)
            //            MessageBox.Show("查无此车", GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            //    }
            //}
            //else
            //{
            try
            {
                paraCardid = Convert.ToInt64(txtQueryCardID.Text);
            }
            catch
            {
                MessageBox.Show(GlobalConst.PARENT_ACCESS_INVALID, GlobalConst.GLOBAL_POPUP_TITLE, MessageBoxButtons.OK);
            }
            }
            DataTable adt = null;
            //dataGridView1.DataSource = mcp.QueryParkInfo(ckid, paraCardid,dateAndTimePicker1,dateAndTimePicker2);

            mcp.InsideCars(paraCardid, carTag, dateAndTimePicker1.DateAndTime, dateAndTimePicker2.DateAndTime, type, ref adt);
            dataGridView1.DataSource = adt.DefaultView;
        }


        /// <summary>
        /// 定时器1查询com1
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                if (serialPort1.BytesToRead > 3)
                {
                    serialPort1.Read(rbuff1, 0, 4);
                    if (rbuff1[0] == 0xFC) //有车开入或开出
                    {
                        timer1.Enabled = false;
                        string cdid = sph.GetCardID(rbuff1).ToString();
                        if (MessageBox.Show(mcp.GetCurrentUserInfoByString(ref cdid, ""), "出入确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            txtInOrOutCardID.Text = cdid;
                            btnIn_Click(null, null);
                        }
                    }
                    timer1.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 定时器2查询com2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                if (serialPort2.BytesToRead > 3)
                {
                    serialPort2.Read(rbuff2, 0, 4);
                    if (rbuff2[0] == 0xFF) //车辆已通过护栏
                    {
                        timer2.Enabled = false;
                        sph.CloseFence(serialPort2);
                    }
                    timer2.Enabled = true;
                }
            }
        }

        #endregion

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void Main_Load(object sender, EventArgs e)
        {

        }

        private void btnOpenCOM1_Click(object sender, EventArgs e)
        {
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Open();
                    rbuff1 = new byte[4];
                    this.timer1.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (serialPort1.IsOpen)
                    btnOpenCOM1.Text = "关闭COM1";
            }
            else
            {
                try
                {
                    serialPort1.Close();
                    this.timer1.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (!serialPort1.IsOpen)
                    btnOpenCOM1.Text = "打开COM1";
            }
        }

        private void btnOpenCOM2_Click(object sender, EventArgs e)
        {
            if (!serialPort2.IsOpen)
            {
                try
                {
                    serialPort2.Open();
                    rbuff2 = new byte[4];
                    this.timer2.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (serialPort2.IsOpen)
                    btnOpenCOM2.Text = "关闭COM2";
            }
            else
            {
                try
                {
                    serialPort2.Close();
                    this.timer2.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (!serialPort2.IsOpen)
                    btnOpenCOM2.Text = "打开COM2";
            }
        }


    }
}
